// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html


import { EventType } from "../common/EventCenter";
import { GameMgr } from "../common/GameMgr";
import { AutoMessageBean, AutoMessageId } from "../net/MessageBaseBean";
import { Config } from "../util/Config";

const { ccclass, property } = cc._decorator;

@ccclass
export default class StartUpCenterController extends cc.Component {


    @property(cc.Sprite)
    progress: cc.Sprite = null
    @property(cc.Label)
    progressLabel: cc.Label = null

    countdownInterval: number = null;//倒计时的 id

    login = false   //登录是否成功
    loding = false  //加载是否成功
    preload = false  //加载是否成功

    protected onLoad(): void {
        cc.resources.preloadDir(Config.buttonRes,cc.SpriteAtlas,(error, items) =>{
            if(error){
                GameMgr.Console.Log('预加载按钮资源失败')
            }else{
                GameMgr.Console.Log('预加载按钮资源成功')
                this.preload = true
                this.jumpHall()
            }
            
        });//提前预加载图片
    }

    protected onEnable(): void {
        this.updateCountdownLabel(0)
        this.startCountdown()
    }

    start() {


    }

    startCountdown() {
        let remainingSeconds = 0;
        this.countdownInterval = setInterval(() => {
            remainingSeconds++;

            if (remainingSeconds > 100) {
                clearInterval(this.countdownInterval);
                this.countdownInterval = null
                this.loding  = true
                // 进度到 100的处理
                this.jumpHall()
                return
            }
            this.updateCountdownLabel(remainingSeconds);
        }, 10);
    }

    updateCountdownLabel(percent: number) {
        this.progressLabel.string = `${percent}%`;
        this.progress.fillRange = percent/100;
    }

    protected onDisable(): void {
        if (this.countdownInterval) {
            clearInterval(this.countdownInterval);
            this.countdownInterval = null
        }
    }
    setLogin(){
        this.login = true
        this.jumpHall()
    }

    jumpHall(){
        //加载成功 并且登录成功 才允许跳转大厅页面
        if(this.loding && this.login && this.preload){

            let autoMessageBean: AutoMessageBean = {
                'msgId': AutoMessageId.JumpHallPage,//跳转进大厅页面
                'data': {'type':1} //1是启动页面跳转的
            }
            GameMgr.Event.Send(EventType.AutoMessage, autoMessageBean);
        }

    }

    // update (dt) {}
}
